<template>
  <div class="product-list-container">
    <!-- 搜索表单 -->
    <el-form :inline="true">
      <el-form-item>
        <el-input
          :clearable="true"
          v-model="SearchId"
          @change="UseIdSearch"
          placeholder="输入入库编号进行搜索"
          :prefix-icon="Search"
        ></el-input>
      </el-form-item>
      <el-form-item style="text-align: right">
        <el-button
          type="primary"
          size="default"
          @click="addDialogOpen"
          v-if="userInfo.identity !== '用户'"
          >添加产品</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 主体表格 -->
    <div class="table">
      <el-table :data="productList" :border="true">
        <el-table-column type="index" width="55"></el-table-column>
        <el-table-column
          label="入库编号"
          align="center"
          type="default"
          prop="product_id"
          min-width="200"
        />
        <el-table-column
          min-width="160"
          label="产品名称"
          align="center"
          type="default"
          prop="product_name"
        />
        <el-table-column
          label="产品类别"
          align="center"
          type="default"
          prop="product_category"
          min-width="120"
        />
        <el-table-column
          min-width="80"
          label="单位"
          align="center"
          type="default"
          prop="product_unit"
        />
        <el-table-column
          label="库存数量"
          align="center"
          type="default"
          prop="product_inwarehouse_number"
          min-width="120"
        >
          <template v-slot="{ row }">
            <el-tag type="danger" v-if="row.product_inwarehouse_number <= 0"> 库存已空 </el-tag>
            <span v-else>{{ row.product_inwarehouse_number }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="产品单价"
          align="center"
          type="default"
          min-width="120"
          prop="product_single_price"
        />
        <el-table-column
          label="库存总价"
          align="center"
          type="default"
          prop="product_all_price"
          min-width="130"
        />
        <el-table-column
          label="库存状态"
          align="center"
          type="default"
          prop="product_status"
          min-width="120"
        >
          <template v-slot="{ row }">
            <el-tag type="danger" v-if="row.product_inwarehouse_number <= 100">库存过少</el-tag>
            <el-tag type="warning" v-else-if="row.product_inwarehouse_number >= 300"
              >库存过剩</el-tag
            >
            <el-tag type="primary" v-else>库存正常</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="入库负责人"
          align="center"
          type="default"
          prop="product_create_person"
          min-width="150"
        />
        <el-table-column
          label="入库时间"
          align="center"
          type="default"
          min-width="210"
          prop="product_create_time"
        >
          <template v-slot="{ row }">
            {{ formaDate(row.product_create_time) }}
          </template></el-table-column
        >
        <el-table-column
          label="最后修改时间"
          align="center"
          type="default"
          prop="product_update_time"
          min-width="210"
        >
          <template v-slot="{ row }">
            {{ row.product_update_time ? formaDate(row.product_update_time) : '未修改' }}
          </template></el-table-column
        >
        <el-table-column
          label="入库备注"
          min-width="210"
          align="center"
          type="default"
          prop="in_memo"
        />
        <el-table-column label="操作" min-width="280" align="center" fixed="right">
          <template v-slot="{ row }">
            <el-button
              type="primary"
              size="default"
              :disabled="
                row.product_out_status === '申请出库' || row.product_inwarehouse_number <= 0
              "
              @click="outDialogOpen(row)"
              >{{ row.product_out_status === '申请出库' ? '正在审核' : '申请出库' }}</el-button
            >
            <el-button
              type="success"
              size="default"
              @click="EditDialog(row)"
              :disabled="row.product_out_status === '申请出库'"
              v-if="userInfo.identity !== '用户'"
              >修改</el-button
            >
            <el-popconfirm
              v-if="userInfo.identity !== '用户'"
              :title="`你确定要删除 ${row.product_name} 吗`"
              confirm-button-text="确认"
              cancel-button-text="取消"
              @confirm="deleteProduct(row)"
              width="250px"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="default"
                  :disabled="row.product_out_status === '申请出库'"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template></el-table-column
        >
      </el-table>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          class="pagination"
          v-model:current-page="page"
          :page-size="10"
          layout="prev, pager, next, jumper,total"
          :total="total"
        />
      </div>
    </div>
  </div>
  <!-- 修改/添加弹窗 -->
  <el-dialog
    @close="close"
    class="dialog"
    v-model="AddOrEditDialog"
    width="45%"
    :title="add ? '添加产品' : '编辑产品'"
  >
    <el-form
      :model="ProductForm"
      class="form"
      :rules="rules"
      label-width="100"
      ref="ProductFormRef"
      style="max-width: 400px; margin: 15px auto"
    >
      <el-form-item label="入库编号" prop="product_id">
        <el-input v-model="ProductForm.product_id" :disabled="!add"></el-input>
      </el-form-item>
      <el-form-item label="产品名称" prop="product_name">
        <el-input v-model="ProductForm.product_name"></el-input>
      </el-form-item>
      <el-form-item label="产品类别" prop="product_category">
        <el-select v-model="ProductForm.product_category">
          <el-option
            v-for="item in ProductCategoryList"
            :key="item"
            :value="item"
            :label="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品单位" prop="product_unit">
        <el-select v-model="ProductForm.product_unit">
          <el-option value="个" label="个"></el-option>
          <el-option value="件" label="件"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="库存数量" prop="product_inwarehouse_number">
        <el-input v-model="ProductForm.product_inwarehouse_number"></el-input>
      </el-form-item>
      <el-form-item label="产品单价" prop="product_single_price">
        <el-input v-model="ProductForm.product_single_price"></el-input>
      </el-form-item>
      <el-form-item label="入库负责人" prop="product_create_person">
        <el-input v-model="ProductForm.product_create_person" :disabled="!add"></el-input>
      </el-form-item>
      <el-form-item label="入库备注" prop="ProductForm">
        <el-input type="textarea" :rows="2" v-model="ProductForm.in_memo"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" size="default" @click="AddOrEditSubmit">确认</el-button>
    </template>
  </el-dialog>
  <el-dialog class="out" v-model="outDialog" @close="close" width="40%" title="申请出库">
    <div class="title">
      <p>您申请出库的产品是： {{ outTitle }}</p>
      <p>产品的库存还有： {{ outNumber }}</p>
    </div>
    <el-form
      :model="outApplyForm"
      :rules="outApplyFormRules"
      style="max-width: 350px; margin: 20px auto"
      label-width="110"
      ref="outApplyFormRef"
    >
      <el-form-item prop="product_out_id" label="申请出库编号:">
        <el-input v-model="outApplyForm.product_out_id"></el-input>
      </el-form-item>
      <el-form-item prop="product_out_number" label="出库数量:">
        <el-input v-model="outApplyForm.product_out_number"></el-input>
      </el-form-item>
      <el-form-item prop="product_out_apply_person" label="出库申请人:">
        <el-input v-model="outApplyForm.product_out_apply_person" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item prop="product_single_price" label="产品单价:">
        <el-input v-model="outApplyForm.product_single_price" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item prop="outApplyForm" label="申请备注:">
        <el-input type="textarea" v-model="outApplyForm.apply_memo"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button
        type="primary"
        size="default"
        @click="outApplyFormSubmit"
        :disabled="outNumber! < outApplyForm.product_out_number!"
        >确认</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  applyOutProductAPI,
  createProductAPI,
  deleteProductAPI,
  editProductAPI,
  getProductListAPI,
  searchProductForIdAPI
} from '@/api/product'
import { getProductAPI } from '@/api/userAdmin'
import { tracking } from '@/utils/operation'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, type FormRules } from 'element-plus'
import moment from 'moment'
import { onMounted, reactive, ref, watch } from 'vue'
import { useUserStore } from '@/stores/user'
const userInfo = useUserStore().UserInfo
// 获取用户信息 跟踪记录使用

const activeName = defineProps(['activeName'])
// 分页器数据
const page = ref<number>(1)
const total = ref<number>(1)
/** 产品列表 */
const productList = ref<ProductAllInfo[]>([])
/** 获取产品列表 */
const getProductList = async () => {
  const res = await getProductListAPI(page.value)
  total.value = res.total!
  productList.value = res.data!
}
// 处理日期
const formaDate = (date: string) => {
  return moment(date).format('YYYY-MM-DD HH:mm:ss')
}
/** 产品入库编号 */
const SearchId = ref<number>()
const UseIdSearch = async () => {
  if (SearchId.value) {
    const res = await searchProductForIdAPI(SearchId.value!)
    productList.value = res.data!
    total.value = productList.value.length
  } else {
    getProductList()
  }
}
/** 修改/添加 弹窗 */
const AddOrEditDialog = ref<boolean>(false)
const close = () => {
  ProductFormRef.value?.resetFields()
  outApplyFormRef.value?.resetFields()
  Object.assign(ProductForm, {
    id: 0,
    product_id: null,
    product_name: '',
    product_category: '',
    product_unit: '',
    product_inwarehouse_number: null,
    product_single_price: null,
    product_create_person: '',
    in_memo: ''
  })
  Object.assign(outApplyForm, {
    id: 0,
    product_out_id: null,
    product_out_number: null,
    product_single_price: null,
    product_out_apply_person: '',
    apply_memo: ''
  })
}
const addDialogOpen = () => {
  add.value = true
  AddOrEditDialog.value = true
}
const EditDialog = (row: productInfo) => {
  Object.assign(ProductForm, row)
  add.value = false
  AddOrEditDialog.value = true
}
/** 添加/修改 表单实例 */
const ProductFormRef = ref()
/** 添加/修改 表单校验 */
const rules = reactive<FormRules<productInfo>>({
  product_id: [{ required: true, message: '请输入入库编号', trigger: 'blur' }],
  product_name: [
    {
      required: true,
      message: '请输入产品名称',
      trigger: 'blur'
    }
  ],
  product_category: [
    {
      required: true,
      message: '请选择产品类别',
      trigger: 'blur'
    }
  ],
  product_unit: [
    {
      required: true,
      message: '请选择产品单位',
      trigger: 'blur'
    }
  ],
  product_inwarehouse_number: [
    {
      required: true,
      message: '请输入库存数量',
      trigger: 'blur'
    }
  ],
  product_single_price: [
    {
      required: true,
      message: '请输入产品单价',
      trigger: 'blur'
    }
  ],
  product_create_person: [
    {
      required: true,
      message: '请输入入库负责人',
      trigger: 'blur'
    }
  ]
})
const AddOrEditSubmit = async () => {
  await ProductFormRef.value.validate()
  // 判断添加 编辑
  if (add.value) {
    await createProductAPI(ProductForm)
    ElMessage({ type: 'success', message: '添加成功' })
    /** 记录操作 */
    tracking('产品', userInfo?.name!, ProductForm.product_name!, '中级', `添加`)
  } else {
    await editProductAPI(ProductForm)
    ElMessage({ type: 'success', message: '修改成功' })
    tracking('产品', userInfo?.name!, ProductForm.product_name!, '中级', `修改`)
  }
  AddOrEditDialog.value = false
  getProductList()
}
/** true为添加，false编辑 */
const add = ref<boolean>(false)
const ProductForm = reactive<productInfo>({
  id: 0,
  product_id: null,
  product_name: '',
  product_category: '',
  product_unit: '',
  product_inwarehouse_number: null,
  product_single_price: null,
  product_create_person: '',
  in_memo: ''
})
/** 申请出库弹窗 */
const outDialog = ref<boolean>(false)
const outTitle = ref<string>('')
const outNumber = ref<number>()
const outDialogOpen = (row: productInfo) => {
  outDialog.value = true
  outTitle.value = row.product_name!
  outNumber.value = row.product_inwarehouse_number!
  // 完善信息
  outApplyForm.product_single_price = row.product_single_price!
  outApplyForm.id = row.id!
  outApplyForm.product_out_apply_person = userInfo.name!
}
/** 出库申请表单 */
const outApplyForm = reactive<outApplyForm>({
  id: 0,
  product_out_id: null,
  product_out_number: null,
  product_single_price: null,
  product_out_apply_person: '',
  apply_memo: ''
})
const outApplyFormRef = ref()
// 申请出库表单校验
const outApplyFormRules = reactive<FormRules<outApplyForm>>({
  product_out_id: [{ required: true, message: '请输入申请出库编号', trigger: 'blur' }],
  product_out_number: [
    {
      required: true,
      message: '请输入出库数量',
      trigger: 'blur'
    }
  ],
  product_out_apply_person: [
    {
      required: true,
      message: '请输入出库申请人',
      trigger: 'blur'
    }
  ],
  product_single_price: [
    {
      required: true,
      message: '请输入产品单价',
      trigger: 'blur'
    }
  ]
})
// 申请出库表单提交
const outApplyFormSubmit = async () => {
  await outApplyFormRef.value.validate()
  await applyOutProductAPI(outApplyForm)
  outDialog.value = false
  ElMessage({ type: 'success', message: '申请成功' })
  tracking('产品', userInfo?.name!, ProductForm.product_name!, '初级', `申请出库`)
  getProductList()
}
/** 删除 */
const deleteProduct = async (row: productInfo) => {
  await deleteProductAPI(row.id!)
  getProductList()
  tracking('产品', userInfo?.name!, row.product_name!, '高级', `删除`)
  ElMessage({ type: 'success', message: '删除成功' })
}

/** const */
const ProductCategoryList = ref<string[]>([])
/** 获取产品列表 */
const getProductCategoryList = async () => {
  const res = await getProductAPI()
  ProductCategoryList.value = JSON.parse(res.data!)
}

watch([page, activeName], () => {
  getProductList()
})
onMounted(() => {
  getProductCategoryList()
  getProductList()
})
</script>

<style scoped lang="scss">
.product-list-container {
  .el-form {
    display: flex;
    justify-content: space-between;
    .el-form-item {
      margin: 0;
    }
  }
  .el-table {
    margin-top: 10px;
  }
  .pagination {
    display: flex;
    justify-content: center;
    margin: 15px;
  }
}
.out {
  .title {
    font-size: 19px;
    text-align: center;
    margin-top: 10px;
    margin-bottom: 30px;
    font-weight: 500;
  }
}
</style>
